import { TypingContext, TypingStateActionType } from '../../store'
import { currentDictGroupIndexAtom } from '../DictChapterButton'
import WordCard from './WordCard'
import Tooltip from '@/components/Tooltip'
import { dictionaries } from '@/resources/dictionary'
import { currentChapterAtom, currentDictIdAtom, currentDictInfoAtom, isReviewModeAtom } from '@/store'
import { Dialog, Transition } from '@headlessui/react'
import * as ScrollArea from '@radix-ui/react-scroll-area'
import { atom, useAtom, useAtomValue } from 'jotai'
import { Fragment, useEffect, useState } from 'react'
import { useContext } from 'react'
import ListIcon from '~icons/tabler/list'
import IconX from '~icons/tabler/x'

const currentDictTitle = atom((get) => {
  const isReviewMode = get(isReviewModeAtom)

  if (isReviewMode) {
    return `${get(currentDictInfoAtom).name} 错题复习`
  } else {
    return `${get(currentDictInfoAtom).name} 第 ${get(currentChapterAtom) + 1} 章`
  }
})

export function ListPreviewButton() {
  // eslint-disable-next-line  @typescript-eslint/no-non-null-assertion
  const { state, dispatch } = useContext(TypingContext)!
  const [isOpen, setIsOpen] = useState(false)
  const [selectedDictName, setSelectedDictName] = useState<string | null>(null)
  const [selectedGroupName, setSelectedGroupName] = useState<string | null>(null)
  const [currentDictId, setCurrentDictId] = useAtom(currentDictIdAtom)
  const chapter = useAtomValue(currentChapterAtom)
  const currentGroupIndex = useAtomValue(currentDictGroupIndexAtom)

  // 每次打开模态框或 currentDictId/chapter 变化时，自动同步标题
  useEffect(() => {
    if (currentDictId) {
      const dict = dictionaries.find((d: any) => d.id === currentDictId)
      if (dict) {
        setSelectedDictName(dict.name)
        setSelectedGroupName(`第${currentGroupIndex + 1}组`)
      }
    }
  }, [currentDictId, currentGroupIndex, isOpen])

  function closeModal() {
    setIsOpen(false)
  }

  function openModal() {
    setIsOpen(true)
    dispatch({ type: TypingStateActionType.SET_IS_TYPING, payload: false })
  }

  return (
    <>
      <Tooltip content="单词预览" placement="top">
        <button
          type="button"
          onClick={openModal}
          className="flex items-center justify-center rounded p-[2px] text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          title="单词预览"
        >
          <ListIcon className="h-6 w-6 text-lg" />
        </button>
      </Tooltip>
      <Transition appear show={isOpen} as={Fragment}>
        <Dialog as="div" className="relative z-50" onClose={closeModal}>
          <Transition.Child
            as={Fragment}
            enter="ease-out duration-300"
            enterFrom="opacity-0"
            enterTo="opacity-100"
            leave="ease-in duration-200"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <div className="fixed inset-0 bg-black bg-opacity-25" />
          </Transition.Child>
          <div className="fixed inset-0 overflow-y-auto">
            <div className="flex min-h-full items-center justify-center p-4 text-center">
              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0 scale-95"
                enterTo="opacity-100 scale-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100 scale-100"
                leaveTo="opacity-0 scale-95"
              >
                <Dialog.Panel className="flex h-[600px] w-auto min-w-[700px] max-w-[90vw] flex-col overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all dark:bg-gray-800">
                  <Dialog.Title as="h3" className="flex items-center justify-between p-4 text-lg font-medium leading-6 dark:text-gray-50">
                    {selectedDictName && selectedGroupName ? `${selectedDictName} - ${selectedGroupName}` : ''}
                    <IconX onClick={closeModal} className="cursor-pointer" />
                  </Dialog.Title>
                  <div className="flex h-full min-w-full overflow-hidden rounded-lg border bg-gray-50 dark:bg-gray-900">
                    <div className="h-full w-full flex-1 overflow-y-auto">
                      <div className="flex flex-col gap-1 p-3">
                        {state.chapterData.words?.map((word, index) => {
                          return <WordCard word={word} key={`${word.name}_${index}`} isActive={state.chapterData.index === index} />
                        })}
                      </div>
                    </div>
                  </div>
                </Dialog.Panel>
              </Transition.Child>
            </div>
          </div>
        </Dialog>
      </Transition>
    </>
  )
}
